<template>
	<div class="table-box">
		<proTable
			ref="proTableRef"
			:columns="columns"
			:toolButton="true"
			:requestApi="api.GetCompanyInfoList"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<template #tableHeader>
				<el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增客户</el-button>
			</template>
			<template #states="scope">
				<el-tag :type="scope.row.states ? 'success' : 'danger'">
					{{ scope.row.states ? "启用" : "禁用" }}
				</el-tag>
			</template>
			<!-- <template #usageTime="scope">
				{{ scope.row.usageTime + "天" }}
			</template> -->
			<template #operation="scope">
				<el-space wrap>
					<el-space wrap>
						<el-tag style="cursor: pointer" @click="openDrawer('编辑', scope.row)"> 编辑 </el-tag>
						<el-tag style="cursor: pointer" :type="scope.row.states ? 'danger' : 'success'" @click="updateStates(scope.row)">
							{{ scope.row.states ? "禁用" : "启用" }}
						</el-tag>
						<el-tag style="cursor: pointer" @click="handleRenewal(scope.row)"> 续期 </el-tag>
						<el-tag style="cursor: pointer" type="info" @click="handleResetPwd(scope.row)"> 重置密码 </el-tag>
						<el-tag style="cursor: pointer" @click="handledetails(scope.row)"> 授权详情 </el-tag>
					</el-space>
				</el-space>
			</template>
		</proTable>
		<el-dialog title="续期" v-model="renewalVisible" width="30%">
			<h3>
				{{ renewalinfo.companyName }}
				<el-tag :type="renewalinfo.states ? '' : 'danger'">
					{{ renewalinfo.states ? "启用" : "禁用" }}
				</el-tag>
			</h3>
			<el-form label-width="100px" label-position="left">
				<el-form-item label="客户类型：">
					<span>{{ renewalinfo.companyTypeName }}</span>
				</el-form-item>
				<el-form-item label="授权码数量：">
					<span>{{ renewalinfo.clientAuthorizationCodeNumber }}台</span>
				</el-form-item>
				<el-form-item label="使用期限：">
					<span>{{ renewalinfo.usageTime }}天</span>
				</el-form-item>
				<el-form-item label="有效周期：">
					<span>{{ renewalinfo.validityPeriod }}</span>
				</el-form-item>
				<el-form-item label="剩余天数：">
					<span>{{ renewalinfo.daysRemaining }}</span>
				</el-form-item>
			</el-form>
			<span>
				<span>*续期至：</span>
				<el-date-picker
					:disabledDate="disablesDate"
					v-model="renewalinfo.authorizeTIme"
					value-format="YYYY-MM-DD"
					type="date"
					placeholder="选择日期"
				/>
			</span>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="renewalVisible = false">取 消</el-button>
					<el-button type="primary" @click="saveRenewal">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<customDrawer ref="drawerRef" />
	</div>
</template>

<script setup lang="tsx" name="basetable">
import { ref, reactive, computed } from "vue";
import api from "@/api/modules/companyInfo";
import useInfoApi from "@/api/modules/userInfo";
import { ColumnProps } from "@/components/ProTable/interface";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useHandleData } from "@/hooks/useHandleData";
import proTable from "@/components/ProTable/index.vue";
import { CirclePlus } from "@element-plus/icons-vue";
// import { dateFormat } from "@/utils/util";
import customDrawer from "./component/customDrawer.vue";
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref();
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	isSelectSuccess: true
});
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 datalist && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
const dataCallback = (data: any) => {
	return {
		list: data.data,
		total: data.totalCount
	};
};
const getCompanyTypeInfoList = async () => {
	let { result } = await api.GetCompanyTypeInfoList();
	if (result.code != 200) {
		return [];
	}
	return result;
};
const router = useRouter();
//续期时弹窗和保存
const renewalVisible = ref(false);
let renewalinfo = ref<any>();
//授权详情
const handledetails = (row: any) => {
	router.push("/system/customer/authorization?id=" + row.id);
};
// 更新客户状态
const updateStates = async (row: any) => {
	let tips = row.states ? "禁用" : "启用";
	let states = !row.states;
	await useHandleData(api.IsStatesCompanyInfo, { id: row.id, states }, `确认要${tips}`);
	proTableRef.value.getTableList();
};
//续期
const handleRenewal = (row: any) => {
	renewalinfo.value = { ...row };
	renewalVisible.value = true;
};
const saveRenewal = async () => {
	await api.CompanyRenewal({
		Id: renewalinfo.value.id,
		AuthorizeEndTIme: renewalinfo.value.authorizeTIme
	});
	renewalVisible.value = false;
	ElMessage.success("续期成功");
	proTableRef.value.getTableList();
};
//重置密码
const handleResetPwd = async (row: any) => {
	await useHandleData(
		useInfoApi.ResetUserInfoPassword,
		{ list: [row.contactsUserId] },
		`将「${row.companyName}」登录密码重置为初始密码：a123456`
	);
};
const headerRender = (row: ColumnProps) => {
	return (
		<el-tooltip class="box-item" effect="dark" content={row.label} placement="top-start">
			{row.label}
		</el-tooltip>
	);
};
// 表格配置项
let columns = computed((): Partial<ColumnProps>[] => {
	let data: Partial<ColumnProps>[] = [
		{ prop: "companyName", label: "客户名称" },
		{ prop: "companyTypeName", label: "客户类型" },
		{ prop: "contactsUserName", label: "联系人" },
		{ prop: "contactsUserTel", label: "联系电话" },
		{ prop: "contactsUserLoginName", label: "登录账号" },
		{ prop: "companyAddress", label: "客户地址" },
		{ prop: "clientAuthorizationCodeNumber", headerRender, label: "授权数量(台)" },
		{ prop: "usageTime", label: "使用期限" },
		{ prop: "authorizeEndTIme", label: "有效周期" },
		{ prop: "daysRemaining", label: "剩余天数" },
		{ prop: "states", label: "状态" },
		{
			prop: "CompanyTypeId",
			label: "客户类型",
			enum: getCompanyTypeInfoList,
			isShow: false,
			search: { el: "select-v2", props: { filterable: true, multiple: true } },
			fieldNames: { label: "companyTypeName", value: "id" }
		},
		{
			prop: "companyName",
			label: "关键字",
			isShow: false,
			search: { el: "input", props: { placeholder: "请输入客户名称" } }
		},
		{ prop: "createUserName", label: "创建人", isShow: false },
		{ prop: "createTime", label: "创建时间", isShow: false },
		{ prop: "operation", label: "操作", width: 200, align: "center", fixed: "right" }
	];
	return data;
});
// 限制续期时间大于当前到期时间
const disablesDate = (time: Date) => {
	const _minTime = new Date(renewalinfo.value.authorizeEndTIme).getTime();
	return time.getTime() < _minTime;
};
// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof customDrawer> | null>(null);
const openDrawer = (title: string, row: any = null) => {
	const params = {
		title,
		isView: title === "编辑",
		row,
		api: undefined,
		getTableList: proTableRef.value.getTableList
	};
	drawerRef.value?.acceptParams(params);
};
</script>
<style>
.table-td-thumb {
	width: 40px;
	height: 40px;
}
</style>
